import Taro, { Component } from '@tarojs/taro'
import { View, Text,Block} from '@tarojs/components'

import { set as setGlobalData, get as getGlobalData } from '../../../static/js/global_data'

import api from '../../../service/api'

import './index.scss'

class index extends Component {
	static options = {
		addGlobalClass: true
	}
	static externalClasses = ['class-box','class-photo','class-item']
	static defaultProps = {
		imgList: [], //上传的图片列表
		imgListMax: 2, //最多传多少张
	}
	constructor() {
		super(...arguments)
		this.state = {};
	}
	componentWillMount(){
		this.setState({
			imgList: this.props.imgList,
			domainImg: getGlobalData('domainImg'),
		})
	}
	changeUploadImg(index){
		if(index == 'add'){ //上传图片
            Taro.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    console.log(res)
                    let formData = {
                        ShopNo: getGlobalData('SHOP_NO'),
                    }
                    api.uploadImage('1907', res.tempFilePaths[0], 'file', formData, (com) => {
                        this.state.imgList.push(this.state.domainImg + com.filepath)
						this.setState({imgList: this.state.imgList})
						this.props.onChangeUploadImg(this.state.imgList)
                    })  
                },
            })
        }else{ // 删除图片
			this.state.imgList.splice(index,1)
			this.props.onChangeUploadImg(this.state.imgList)
        }
	}
	render() {
		return (
			<View className='chooseImage class-box'>
				{this.props.imgList&&this.props.imgList.map((item,i) => (
					<View className='class-item item-img-box' key={'imgList' + i}>
						<Image src={item}></Image>
						<Icon size='20' color='#f00' className='icon-clear' type='clear'  onClick={this.changeUploadImg.bind(this,i)}></Icon>
					</View>
				))}
				{this.props.imgList.length < this.props.imgListMax && <View className='class-item' onClick={this.changeUploadImg.bind(this,'add')}><Text className='class-photo'></Text></View>}
				{this.props.children}
			</View>
		)
	}
}
export default index;